package com.example.goodpet.home.homeRecommend.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.example.goodpet.R;
import com.example.goodpet.activity.SearchActivity;
import com.example.goodpet.base.BaseFragment;
import com.example.goodpet.bean.UserPetInfo;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.common.EndlessRecyclerOnScrollListener;
import com.example.goodpet.common.LoadMoreWrapper;
import com.example.goodpet.home.homeRecommend.adapter.HomeRecommendFragmentAdapter;
import com.example.goodpet.home.homeRecommend.adapter.viewholder.BannerViewHolder;
import com.example.goodpet.home.homeRecommend.adapter.viewholder.ChannelViewHolder;
import com.example.goodpet.home.homeRecommend.adapter.viewholder.MainChannelViewHolder;
import com.example.goodpet.home.homeRecommend.adapter.RecommendRecycleViewAdapter;
import com.example.goodpet.home.homeRecommend.bean.ResultBeanData;
import com.example.goodpet.home.homeRecommend.bean.Species;
import com.example.goodpet.service.HomeService;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.TimeSeed;
import com.example.goodpet.utils.UIUtils;
import com.github.gzuliyujiang.dialog.DialogColor;
import com.github.gzuliyujiang.dialog.DialogConfig;
import com.github.gzuliyujiang.dialog.DialogStyle;
import com.github.gzuliyujiang.wheelpicker.AddressPicker;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode;
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity;
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity;
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomeRecommendFragment extends BaseFragment {
    private String TAG = this.getClass().getSimpleName();

    //用来获取主页数据
    private OkHttpClient okHttpClient;
    private Retrofit retrofit;
    private HomeService homeService;
    private ResultBeanData.ResultDTO resultBean;

    //筛选列表的三个按钮
    private TextView tv_screening_location;
    private TextView tv_screening_search;
    private TextView tv_screening_species;

    //主页上方的recyclerview
    private RecyclerView rvParent;
    //用来展示宠物信息的recyclerview
    private RecyclerView rvPet;
    //用来获取宠物信息
    private Retrofit retrofit1;
    private HomeService homeService1;
    //VLayout
    private VirtualLayoutManager layoutManager;
    //主页上方适配器集合
    private List<DelegateAdapter.Adapter> subAdapters = new LinkedList();
    //宠物信息适配器集合
    private List<DelegateAdapter.Adapter> subAdaptersPet = new LinkedList();
    //宠物信息列表集合，访问服务器获取
    private static List<UserPetInfo> userPetInfos = new ArrayList<>();
    //用来获取布局
    private LayoutInflater mLayoutInflater;
    //speciesId 默认为0  0在数据库表示查询任意种类的宠物
    private int speciesId=0;
    //location默认为tv_screening_location外显文本
    private String location="地区";
    private long seed= TimeSeed.Get();

    @Override
    public View initView() {
        View view = View.inflate(mContext, R.layout.fragment_home_recommend, null);

        tv_screening_location = view.findViewById(R.id.tv_screening_location);
        tv_screening_search = view.findViewById(R.id.tv_screening_search);
        tv_screening_species = view.findViewById(R.id.tv_screening_species);
        rvParent=view.findViewById(R.id.rv_parent);
        rvPet=view.findViewById(R.id.rv_pet);
        mLayoutInflater = LayoutInflater.from(mContext);


        //初始化监听
        initListener();
        return view;
    }


    /**
     * 初始化主页面Fragment的数据
     */

    @Override
    public void initData() {
        //获取主页上方数据
        retrofit = new Retrofit.Builder().baseUrl(Constants.JSON_URL).build();
        homeService = retrofit.create(HomeService.class);
        Call<okhttp3.ResponseBody> call = homeService.getHomeJson();
        call.enqueue(new Callback<okhttp3.ResponseBody>() {
            @Override
            public void onResponse(Call<okhttp3.ResponseBody> call, Response<okhttp3.ResponseBody> response) {
                try {
                    //获取成功，对数据进行处理
                    okhttp3.ResponseBody body = response.body();
                    if (body!=null){
                        processData(body.string());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<okhttp3.ResponseBody> call, Throwable t) {
                Log.e(TAG, "onFailure: 请求失败"+t.getMessage() );
                UIUtils.toast("网络通信失败",false);
            }

        });
        super.initData();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void processData(String json){
//        Gson提供的Gson对象
        Gson gson = new Gson();
        //反序列化
        ResultBeanData resultBeanData = gson.fromJson(json, ResultBeanData.class);
        resultBean=resultBeanData.getResult();

        if(resultBean!=null){
            //有数据
            //初始化主页上方的页面
            initVLayoutRvParent();
            //根据location和species初始化宠物信息数据
            initPetData();

        }else{
            UIUtils.toast("未获取到页面数据",false);
        }

    }

    /**
     * 根据location和species获取宠物数据，赋值给userPetInfos
     */
    private void initPetData() {
        //如果location没有数据，就同步定位的位置信息
        if("地区".equals(location)){
            //如果定位失败，则提示相应的信息
            if("".equals(MyApplication.location)){
            }else{
                //定位成功，location修改成相应的定位，tv_screening_location外显文本也发生相应改变
                location=MyApplication.location;
            }
        }

        tv_screening_location.setText(location);


        retrofit1 = RetrofitSingleton.getRetrofitConstance();
        homeService1 = retrofit1.create(HomeService.class);
        homeService1
                .selectSpecificUserPetInfo(seed,location, speciesId,1)
                .enqueue(new Callback<com.example.goodpet.bean.ResponseBody<List<UserPetInfo>>>() {
                    @Override
                    public void onResponse(Call<com.example.goodpet.bean.ResponseBody<List<UserPetInfo>>> call, Response<com.example.goodpet.bean.ResponseBody<List<UserPetInfo>>> response) {
                        com.example.goodpet.bean.ResponseBody<List<UserPetInfo>> body = response.body();
                        if (body.getCode() == 200) {
//                            Log.e(TAG, "onResponse: "+body.getData() );
                            userPetInfos = body.getData();
                        } else {
                            userPetInfos = null;
                            UIUtils.toast("未获取到宠物信息！", false);
                        }
                        //获取数据成功后初始化显示宠物信息的recyclerview
                        initVLayoutRvPet();
                    }

                    @Override
                    public void onFailure(Call<com.example.goodpet.bean.ResponseBody<List<UserPetInfo>>> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t);
                        UIUtils.toast("网络通信失败1", false);
                    }
                });

    }

    /**
     * 初始化主页上方页面
     */
    private void initVLayoutRvParent() {
        //1.设置总布局管理器
        layoutManager = new VirtualLayoutManager(mContext);
        rvParent.setLayoutManager(layoutManager);
        //2.设置回收池大小（相同类型的View可以复用，防止多次创建ItemView）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 10);
        rvParent.setRecycledViewPool(viewPool);
        //3.逐个设置子模块适配器
        addMainChannelAdapter();
        addChannelAdapter();
        addBannerAdapter();

        //4.设置总适配器
        DelegateAdapter mainAdapter = new DelegateAdapter(layoutManager, true);
        mainAdapter.setAdapters(subAdapters);
        rvParent.setAdapter(mainAdapter);

    }

    /**
     * 初始化展示宠物信息的页面
     */
    private void initVLayoutRvPet() {
        //1.设置总布局管理器
        layoutManager = new VirtualLayoutManager(mContext);
        rvPet.setLayoutManager(layoutManager);
        //2.设置回收池大小（相同类型的View可以复用，防止多次创建ItemView）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 10);
        rvPet.setRecycledViewPool(viewPool);
        //3.逐个设置子模块适配器
        subAdaptersPet.clear();
        addPetAdapter();

        //4.设置总适配器
        DelegateAdapter mainAdapter = new DelegateAdapter(layoutManager, true);
        mainAdapter.setAdapters(subAdaptersPet);
        rvPet.setAdapter(mainAdapter);

    }

    /**
     * 添加宠物信息的适配器到展示宠物信息的页面
     */
    private void addPetAdapter() {
        GridLayoutHelper helper = new GridLayoutHelper(2);

        RecommendRecycleViewAdapter adapter = new RecommendRecycleViewAdapter(mContext, userPetInfos);
        LoadMoreWrapper loadMoreWrapper = new LoadMoreWrapper(adapter){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return helper;
            }
        };
//        rvParent.setAdapter(loadMoreWrapper);
        subAdaptersPet.add(loadMoreWrapper);


        rvPet.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING);
                homeService1.selectSpecificUserPetInfo(seed,location, speciesId, ++loadMoreWrapper.page)
                        .enqueue(new Callback<ResponseBody<List<UserPetInfo>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<UserPetInfo>>> call, Response<ResponseBody<List<UserPetInfo>>> response) {
                        ResponseBody<List<UserPetInfo>> body1 = response.body();
//                        int code=body1.getCode();
//                        Log.e(TAG, "onResponse: "+code );
                        if (body1.getCode()==200){
                            List<UserPetInfo> data1 = body1.getData();
//                            Log.e(TAG, "onResponse: "+data1);
                            userPetInfos.addAll(data1);
                            loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
                        }else if (body1.getCode()==404){
                            loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_END);
                        }

                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<UserPetInfo>>> call, Throwable t) {
                        UIUtils.toast("连接服务器失败",false);
                    }
                });
            }
        });

    }

    /**
     * 添加轮播图的适配器到主页上方的页面
     */
    private void addBannerAdapter() {
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(1);
        HomeRecommendFragmentAdapter adapter = new HomeRecommendFragmentAdapter(){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return gridLayoutHelper;
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new BannerViewHolder(mContext, mLayoutInflater.inflate(R.layout.banner_viewpager, null));
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                BannerViewHolder bannerViewHolder = (BannerViewHolder) holder;
                bannerViewHolder.setData(resultBean.getBannerInfo());
            }
        };
        subAdapters.add(adapter);
    }

    /**
     * 添加主要图标的适配器到主页上方的页面
     */
    private void addMainChannelAdapter() {
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(3);
        gridLayoutHelper.setBgColor(Color.WHITE);
        HomeRecommendFragmentAdapter adapter = new HomeRecommendFragmentAdapter(){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return gridLayoutHelper;
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new MainChannelViewHolder(mContext,mLayoutInflater.inflate(R.layout.channel_main_item,null));
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                MainChannelViewHolder mainChannelViewHolder = (MainChannelViewHolder) holder;
                mainChannelViewHolder.setData(resultBean.getMainChannelInfo());
            }
        };
        subAdapters.add(adapter);
    }

    /**
     * 添加图标的适配器到主页上方的页面
     */
    private void addChannelAdapter() {
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(5);
        gridLayoutHelper.setBgColor(Color.WHITE);
        HomeRecommendFragmentAdapter adapter = new HomeRecommendFragmentAdapter(){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return gridLayoutHelper;
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new ChannelViewHolder(mContext,mLayoutInflater.inflate(R.layout.channel_item,null));
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                ChannelViewHolder channelViewHolder = (ChannelViewHolder) holder;
                channelViewHolder.setData(resultBean.getChannelInfo());
            }
        };
        subAdapters.add(adapter);
    }


    /**
     * 主要初始化筛选和搜索的点击事件
     */
    public void initListener(){
        tv_screening_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogConfig.setDialogStyle(DialogStyle.Three);
                DialogConfig.setDialogColor(new DialogColor()
                        .cancelTextColor(0xFF999999)
                        .okTextColor(0xFF0099CC));

                AddressPicker picker = new AddressPicker(getActivity());
                picker.setAddressMode(AddressMode.PROVINCE_CITY);

                picker.setOnAddressPickedListener(new OnAddressPickedListener() {
                    @Override
                    public void onAddressPicked(ProvinceEntity province, CityEntity city, CountyEntity county) {
                        /**
                         * 监测到地区改变，外显按钮文本进行相应的改变后，根据用户选择重新初始化对应的宠物信息
                         */
                        if(null!=city){
                            tv_screening_location.setText(city.getName());
                        }else{
                            tv_screening_location.setText(province.getName());
                        }
//                        Log.e(TAG, "onAddressPicked: "+tv_screening_location.getText().toString() );
                        location=tv_screening_location.getText().toString();
//                        UIUtils.toast(location,false);
                        initPetData();
                    }
                });
                picker.show();
            }
        });

        tv_screening_species.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                List<Species> data = new ArrayList<>();
                data.add(new Species(0,"暂不选择"));
                data.add(new Species(1,"流浪的喵"));
                data.add(new Species(2,"流浪的汪"));
                data.add(new Species(3,"被抛弃的喵"));
                data.add(new Species(4,"被抛弃的汪"));
                data.add(new Species(5,"其他"));
                OptionPicker picker = new OptionPicker(getActivity());
                picker.setTitle("宠物分类");
                picker.setBodyWidth(160);
                picker.setData(data);
                picker.setDefaultPosition(0);
                picker.setOnOptionPickedListener(new OnOptionPickedListener() {
                    @Override
                    public void onOptionPicked(int position, Object item) {
                        /**
                         * 监测到种类改变，外显按钮文本进行相应的改变 且 种类的标志进行相应的改变后，根据用户选择重新初始化对应的宠物信息
                         */
                        tv_screening_species.setText(((Species)item).getSpecies());
                        speciesId=((Species)item).getId();
//                        UIUtils.toast(String.valueOf(speciesId),false);
                        initPetData();
                    }
                });
                picker.show();

            }
        });

        tv_screening_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                UIUtils.toast("搜索",false);
                Intent intent=new Intent(mContext, SearchActivity.class);
                intent.putExtra("type",1);
                mContext.startActivity(intent);
            }
        });
    }
}
